﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Administration.Catalog.recUserSectorhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Administration.Catalog
{

    public class recUserSectorhandler : SIPO.Web.BaseHandler
    {
        private recUserSectorRepo userSectorDal = new recUserSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recDebtorSectorRepo DebtorSectorDal = new recDebtorSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insertbyuser"):
                    context.Response.Write(InsertByUser(context, jObj));
                    break;
                case ("getdatabyuserid"):
                    context.Response.Write(GetDataByUserId(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string InsertByUser(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                int UserID = Convert.ToInt32(jo["UserID"]);
                List<recUserSector> roleUsers = userSectorDal.GetListByUserId(UserID);
                roleUsers.ForEach(delegate(recUserSector domain)
                {
                    userSectorDal.Delete(domain.UserSectorID);
                });
                int DebtorID = Convert.ToInt32(jo["DebtorID"]);
                List<recDebtorSector> DebtorSector = new List<recDebtorSector>();
                if (DebtorID != -1)
                {
                    DebtorSector = DebtorSectorDal.GetListByDebtor(DebtorID);
                }
                    string[] subSubIds = Convert.ToString(jo["SubSubSectorID"]).Split(',');
                  
                for (int i = 0; i < subSubIds.Length; i++)
                {
                    recUserSector obj = new recUserSector();
                    try
                    { 
                                      
                    obj.SubSubSectorID = Convert.ToInt32(subSubIds[i]);
                    if (DebtorID != -1)
                    {
                        recDebtorSector debtorsector = DebtorSector.Find(x => x.SubSubSectorID == obj.SubSubSectorID); // ambil debtor sectorid               
                        obj.DebtorSectorID = debtorsector.DebtorSectorID; 
                    }
                    else
                    {
                        obj.DebtorSectorID = null; 
                    }
                    obj.UserID = UserID; 
                    obj.CreatedDate = DateTime.Now;
                    obj.CreatedBy = base.UserLoggedIn;

                    userSectorDal.Save(obj);
                    }
                    catch
                    {
                        helper.IsSuccess = true;
                        helper.Message = "Data berhasil disimpan!";
                    }
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil disimpan!";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert By User Sector";
                log.LogMessage = helper.Message;
                log.LogSource = "recUserSectorhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        public string GetDataByUserId(HttpContext context)
        {
            int UserID = 0;
            int.TryParse(context.Request.Params["UserID"], out UserID);

            List<recUserSector> list = userSectorDal.GetListByUserId(UserID);

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }

    }

}